﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;

namespace TMSIM.Client.BizGIS.Business
{
    public class TOCControlHelper1
    {
        private AxMapControl m_mapControl = null;
        private TreeView m_treeView = null;
        private bool m_CanChange = false;
        private int m_currentLayerCount = 0;
        /// <summary>
        /// 关联的地图控件
        /// </summary>
        public AxMapControl BuddyMapControl
        {
            get { return m_mapControl; }
            set { m_mapControl = value; }
        }

        /// <summary>
        /// 描述：设置关联的地图控件
        /// </summary>
        /// <param name="inMapControl">地图控件</param>
        /// <param name="treeView">TreeView控件</param>
        /// <param name="mapDocument">地图的标题</param>
        public void SetBuddyMapControl(AxMapControl inMapControl,TreeView treeView,string mapDocument)
        {
            try
            {
                m_mapControl = inMapControl;
                m_treeView = treeView;

                m_treeView.Nodes.Clear();
                m_treeView.Nodes.Add(mapDocument, mapDocument);
                m_treeView.Nodes[0].Checked = false;

                m_mapControl_OnMapReplaced(null, null);

                m_mapControl.OnMapReplaced +=
                    new IMapControlEvents2_Ax_OnMapReplacedEventHandler(m_mapControl_OnMapReplaced);
                m_mapControl.OnAfterDraw += new IMapControlEvents2_Ax_OnAfterDrawEventHandler(m_mapControl_OnAfterDraw);
                m_treeView.AfterCheck += new TreeViewEventHandler(m_treeView_AfterCheck);
            }
            catch(Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的SetBuddyMapControl出错！",ex);
            }
        }
        /// <summary>
        /// 描述：添加车辆信息图层到图层控件中
        /// </summary>
        public void AddCarInfoLayer(AxMapControl inMapControl)
        {
            try
            {
                m_mapControl = inMapControl;
                for (int i = 0; i < m_mapControl.LayerCount; i++)
                {
                    if (m_mapControl.get_Layer(i).Name == "车辆信息")
                    {
                        m_treeView.Nodes[0].Nodes.Add("车辆信息", "车辆信息");
                        m_treeView.Nodes[0].Checked = false;
                        return;
                    }
                }
                SysCommon.Global.mainLog.Error("没有找到可以添加的车辆信息图层");
            }
            catch(Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的AddCarInfoLayer出错！", ex);
            }
        }

        void m_mapControl_OnAfterDraw(object sender, IMapControlEvents2_OnAfterDrawEvent e)
        {
            try
            {
                if (m_currentLayerCount == m_mapControl.LayerCount) return;

                if (!m_CanChange) return;

                //for (int i = 0; i < m_mapControl.LayerCount;i++ )
                //{
                //    if (m_mapControl.get_Layer(i).Name == "车辆信息")
                //        m_treeView.Nodes[0].Nodes.Add("车辆信息", "车辆信息");
                //}
                //    m_treeView.Nodes.Clear();
                //m_CanChange = false;
                //LoopMapControlLayers(m_treeView);
                //m_currentLayerCount = m_mapControl.LayerCount;
                //if (m_treeView.Nodes.Count == 0) return;
                //m_CanChange = true;
            }
            catch(Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的m_mapControl_OnAfterDraw出错！", ex);
            }
        }

        /// <summary>
        /// 描述：控制图层的显示与否
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_treeView_AfterCheck(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (!m_CanChange) return;
                
                TreeNode tn = e.Node;
                string node_name = tn.Name;

                IFeatureLayer flyr = GetFeatureLayer(node_name);
                if (flyr == null)
                {
                    m_CanChange = false;
                    int count = tn.Nodes.Count;
                    bool isChecked = tn.Checked;

                    m_CanChange = false;
                    for (int i = 0; i < count; i++)
                    {
                        m_CanChange = true;
                        tn.Nodes[i].Checked = isChecked;

                        if(i==count-2)m_CanChange = true;
                    }
                    m_CanChange = true;
                }
                else
                {
                    flyr.Visible = tn.Checked;
                    m_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography,flyr,null);
                }

                //控制子节点
                if (tn.Nodes.Count > 0)
                {
                    m_CanChange = false;
                    foreach (TreeNode n1 in tn.Nodes)
                    {
                        n1.Checked = tn.Checked;
                    }
                    m_CanChange = true;
                }

                //控制父节点
                if (null != tn.Parent)
                {
                    m_CanChange = false;
                    TreeNode pn = tn.Parent;
                    bool isCheckAll = true;
                    bool tmp = tn.Checked;
                    foreach (TreeNode n2 in pn.Nodes)
                    {
                        if (tmp == n2.Checked) continue;
                        isCheckAll = false;
                        break;
                    }
                    if (isCheckAll) pn.Checked = tmp;
                    m_CanChange = true;
                }
            }
            catch(Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的m_treeView_AfterCheck出错！", ex);
            }
        }

        /// <summary>
        /// 描述：当地图控件的地图更换时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_mapControl_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
        {
            try
            {
                m_CanChange = false;
                LoopMapControlLayers(m_treeView);
                m_currentLayerCount = m_mapControl.LayerCount;
                if (m_treeView.Nodes.Count == 0) return;
                m_CanChange = true;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的m_mapControl_OnMapReplaced出错！", ex);
            }

        }

        /// <summary>
        /// 描述：向TreeView中添加对应图层节点
        /// </summary>
        /// <param name="treeView">TreeView控件</param>
        private void LoopMapControlLayers(TreeView treeView)
        {
            try
            {
                treeView.CheckBoxes = true;
                AddGroupLayers(treeView);
                //treeView.ExpandAll();
                if (treeView.Nodes.Count == 0) return;
                treeView.Nodes[0].Expand();
                TreeNode pn = treeView.Nodes[0];

                //控制父节点
                if (null != pn)
                {
                    m_CanChange = false;
                    bool isCheckAll = true;
                    int is_First = 1;
                    bool tmp = false;
                    foreach (TreeNode n2 in pn.Nodes)
                    {
                        if (is_First == 1)
                        {
                            tmp = n2.Checked;
                            is_First = 2;
                        }
                        if (tmp == n2.Checked) continue;
                        isCheckAll = false;
                        break;
                    }
                    if (isCheckAll) pn.Checked = tmp;
                    m_CanChange = true;
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的LoopMapControlLayers出错！", ex);
            }


        }
    
        
        /// <summary>
        /// 描述：向TreeView中添加Group Layers
        /// </summary>
        /// <param name="treeView">TreeView控件</param>
        private void AddGroupLayers(TreeView treeView)
        {
            try
            {
                //check the treeView
                if (treeView.Nodes.Count == 0)
                {
                    treeView.Nodes.Add("广东省", "广东省");
                    //treeView.Nodes["广东省"].Checked = true;
                }
                //treeView.Nodes[0].Expand();

                try
                {
                    //layers' count
                    int lyr_count = m_mapControl.LayerCount;
                    //layer's name
                    string lyr_name = "";
                    //layer to be added
                    ILayer lyr = null;
                    //loop through the group layers
                    //get enum layer
                    UID uid = new UID();
                    uid.Value = "{EDAD6644-1810-11D1-86AE-0000F8751720}";
                    IEnumLayer enLyr = m_mapControl.Map.get_Layers(uid, true);
                    lyr = enLyr.Next();

                    if (lyr != null)
                    {
                        do
                        {
                            lyr_name = lyr.Name;
                            TreeNode tree_n = treeView.Nodes[0].Nodes.Add(lyr_name, lyr_name);
                            tree_n.Checked = lyr.Visible;
                            lyr = enLyr.Next();
                        } while (lyr != null);
                    }
                }
                catch(Exception ex)
                {
                    SysCommon.Global.mainLog.Error("地图没有分层显示！",ex);
                }

                AddFeatureLayers(treeView);
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的AddGroupLayers出错！", ex);
            }


        }

        /// <summary>
        /// 描述：向TreeView中添加Feature Layers
        /// </summary>
        /// <param name="treeView">TreeView控件</param>
        private void AddFeatureLayers(TreeView treeView)
        {
            try
            {
                //node key string
                string flyr_Key = "";
                string node_Key = "";
                string fCls_Name = "";

                //get enum layer
                UID uid =new UID();
                uid.Value = "{40A9E885-5533-11d0-98BE-00805F7CED21}";
                IEnumLayer enLyr = m_mapControl.Map.get_Layers(uid, true);

                //loop througth the layers
                IFeatureLayer flyr = (IFeatureLayer)enLyr.Next();
                IFeatureClass fCls = null;
                if(flyr!=null)
                {
                    while(flyr != null)
                    {
                        fCls = flyr.FeatureClass;
                        //the name showed in the toc
                        flyr_Key = flyr.Name;
                        //the name of the feature class
                        fCls_Name = fCls.AliasName;
                        //the name of the last two charactors
                        fCls_Name = fCls_Name.Substring(fCls_Name.Length - 2, 2);
                        //get the node key
                        node_Key = "";
                        node_Key = GetNodeKey(fCls_Name);

                        if (node_Key != "" && treeView.Nodes[0].Nodes.ContainsKey(node_Key))
                        {
                            TreeNode tn=treeView.Nodes[0].Nodes[node_Key].Nodes.Add(flyr_Key, flyr_Key);
                            tn.Checked = flyr.Visible;
                            if (flyr.Visible) treeView.Nodes[0].Nodes[node_Key].Checked = true;
                        }
                        else
                        {
                            TreeNode tn=treeView.Nodes[0].Nodes.Add(flyr_Key, flyr_Key);
                            tn.Checked = flyr.Visible;
                        }

                        flyr =(IFeatureLayer)enLyr.Next();

                    }
                    //treeView.CollapseAll();
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的AddFeatureLayers出错！", ex);
            }


        }

        /// <summary>
        /// 描述：获取Group Layers的节点名称
        /// </summary>
        /// <param name="inString"></param>
        /// <returns></returns>
        private string GetNodeKey(string inString)
        {
            string reString = "";
            try
            {
                switch(inString)
                {
                    case "GZ":
                        reString = "广州市";
                        break;
                    case "SG":
                        reString = "韶关市";
                        break;
                    case "SZ":
                        reString = "深圳市";
                        break;
                    case "ZH":
                        reString = "珠海市";
                        break;
                    case "ST":
                        reString = "汕头市";
                        break;
                    case "JY":
                        reString = "揭阳市";
                        break;
                    case "FS":
                        reString = "佛山市";
                        break;
                    case "JM":
                        reString = "江门市";
                        break;
                    case "ZJ":
                        reString = "湛江市";
                        break;
                    case "MM":
                        reString = "茂名市";
                        break;
                    case "ZQ":
                        reString = "肇庆市";
                        break;
                    case "YF":
                        reString = "云浮市";
                        break;
                    case "HZ":
                        reString = "惠州市";
                        break;
                    case "MZ":
                        reString = "梅州市";
                        break;
                    case "SW":
                        reString = "汕尾市";
                        break;
                    case "HY":
                        reString = "河源市";
                        break;
                    case "YJ":
                        reString = "阳江市";
                        break;
                    case "QY":
                        reString = "清远市";
                        break;
                    case "DG":
                        reString = "东莞市";
                        break;
                    case "ZS":
                        reString = "中山市";
                        break;
                    case "CZ":
                        reString = "潮州市";
                        break;
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的GetNodeKey出错！", ex);
            }

            return reString;
        }

        /// <summary>
        /// 描述：根据图层名获取对应的图层
        /// </summary>
        /// <param name="flyr_name"></param>
        /// <returns></returns>
        private IFeatureLayer GetFeatureLayer(string flyr_name)
        {
            try
            {
                if (flyr_name == "车辆信息")
                {
                    for (int i = 0; i < m_mapControl.LayerCount; i++)
                    {
                        if (m_mapControl.get_Layer(i).Name == flyr_name)
                            return (IFeatureLayer)m_mapControl.get_Layer(i);
                    }
                }

                //get enum layer
                UID uid = new UID();
                uid.Value = "{40A9E885-5533-11d0-98BE-00805F7CED21}";
                IEnumLayer enLyr = m_mapControl.Map.get_Layers(uid, true);

                //loop througth the layers
                IFeatureLayer flyr = (IFeatureLayer)enLyr.Next();

                if(flyr!=null)
                {
                    do
                    {
                        if (flyr.Name == flyr_name) return flyr;
                        flyr = (IFeatureLayer)enLyr.Next();
                    } while (flyr != null);
                }

            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用TOCControlHelper的GetFeatureLayer出错！", ex);
            }
            return null;
        }
    }
}
